package co.edu.unad.persistence;

import java.util.List;

import javax.persistence.Column;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import co.edu.unad.entities.Usuario;

@Repository
public class UsuarioDAO {

	@Autowired
	private SessionFactory sessionFactory;

	/**
	 * Get Hibernate Session Factory
	 * 
	 * @return SessionFactory - Hibernate Session Factory
	 */
	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	/**
	 * Set Hibernate Session Factory
	 * 
	 * @param sessionFactory
	 *            SessionFactory - Hibernate Session Factory
	 */
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	public Usuario createUser(Usuario usuario) {

		Session session = getSessionFactory().openSession();
		Transaction transaction = null;
		try {
			transaction = session.beginTransaction();
			session.save(usuario);
			transaction.commit();
			System.out.println("Records inserted sucessessfully");
		} catch (HibernateException e) {
			transaction.rollback();
			e.printStackTrace();
			usuario = null;
		} finally {
			session.close();
		}
		return usuario;
	}

	public Usuario consultarUsuarioPorLoginYPassword(String usuario, String password) {

		Usuario resultado = null;

		final Session session = sessionFactory.getCurrentSession();
		final Criteria criteria = session.createCriteria(Usuario.class);

		criteria.add(Restrictions.eq("login", usuario));
		criteria.add(Restrictions.eq("password", password));

		List<Usuario> list = criteria.list();

		if (list != null && list.size() > 0) {
			resultado = list.get(0);
		}
		return resultado;
	}

}
